<?php
class Admincpanel_Model_Privilege extends Zend_Db_Table
{
	protected $_name = 'user_group_privileges';
	//protected $_primary = 'id';
	protected $_arrParam = array();
	protected $_db;
	
	public function __construct($arrParam = null)
	{
		$this->_filter = new Zend_Filter_StripTags();
		if ( ! empty($arrParam))
		{
			foreach ($arrParam as $key => $value)
			{
				if ( ! in_array($key, array('module', 'controller', 'action', 'task')))
				{
					$this->_arrParam[$key] = $this->_filter->filter($value);
				}
			}
			unset($arrParam);
		}
		$this->_db = Zend_Registry::get('connectDb');
	}
	
	public function createpres()
	{
		if ($this->_arrParam['fullname'] == '' OR $this->_arrParam['usremail'] == '' 
				OR $this->_arrParam['usrname'] == '' OR $this->_arrParam['usrgroup'] == '')
		{
			return 'required';
		}
		
		if ($this->isExistAdd())
		{
			return 'exist';	
		}
		
		$email = new Zend_Validate_EmailAddress();
		if ( ! $email->isValid($this->_arrParam['usremail']))
		{
			return 'invalidemail';
		}
		
		$row =  $this->fetchNew();
		$row->full_name 	= $this->_arrParam['fullname'];
		$row->username	 	= $this->_arrParam['usrname'];
		$row->email 		= $this->_arrParam['usremail'];
		$row->group_id	 	= $this->_arrParam['usrgroup'];
		$row->status		= 1;
		$row->password		= md5(1);
						
		$row->save();
		$this->_db->query("ANALYZE TABLE `users`"); // after insert
		return 'ok';
	}
	
	private function isExistAdd()
	{
		$select = $this->_db->select()
				->from('users', array('id'))
				->where('username = ?', $this->_arrParam['usrname'], STRING)
				->orWhere('email = ?', $this->_arrParam['usremail'], STRING)
				->limit(1);
		$result = $this->_db->fetchRow($select);
		return ( ! empty($result)) ? true : false;
	}
	
	public function listing()
	{
		$nbrows = $this->getAll($arrParam);
		
		$select = $this->_db->select()
				->from('user_group_privileges as ugp', array('id', 'status'))
				->joinLeft('privileges as p', 'p.id = ugp.privilege_id', array('name'))
				->joinLeft('user_group as g', 'g.id = ugp.group_id', array('group_name'))
				->order('g.group_name', 'ASC')
				->limit($this->_arrParam['limit'], $this->_arrParam['start']);
		if ($this->_arrParam['group'])
		{
			$select->where('g.id = ?', $this->_arrParam['group'], INTEGER);
		}
		$result = $this->_db->fetchAll($select);
		if ( ! empty($result))
		{
			foreach ($result as $row)
			{
				$arr[] = $row;
			}
			$jsonresult = json_encode($arr);
			return '({"total":"' .$nbrows. '","results":' .$jsonresult. '})';
		}
		else
		{
			return '({"total":"0", "results":""})';	
		}
	}
	
	private function getAll()
	{
		$select = $this->_db->select()
				->from('user_group_privileges as ugp', array('COUNT(ugp.status) as allupg'))
				->joinLeft('privileges as p', 'p.id = ugp.privilege_id', array())
				->joinLeft('user_group as g', 'g.id = ugp.group_id', array());
		if ($this->_arrParam['group'])
		{
			$select->where('g.id = ?', $this->_arrParam['group'], INTEGER);
		}
		$result = $this->_db->fetchRow($select);
		return $result['allupg'];
	}
	
	public function grouplist()
	{
		$select = $this->_db->select()
				->from('user_group', array('id', 'group_name'))
				->where('id != 1')
				->order('group_name', 'ASC');
		$result = $this->_db->fetchAll($select);
		if ( ! empty($result))
		{
			foreach ($result as $row)
			{
				$arr[] = $row;
			}
			$jsonresult = json_encode($arr);
			return '({"results":'.$jsonresult.'})';
		}
		return false;
	}
	
	public function plist()
	{
		$select = $this->_db->select()
				->from('privileges', array('id', 'name'))
				->order('controller', 'ASC');
		$result = $this->_db->fetchAll($select);
		if ( ! empty($result))
		{
			foreach ($result as $row)
			{
				$arr[] = $row;
			}
			$jsonresult = json_encode($arr);
			return '({"results":'.$jsonresult.'})';
		}
		return false;
	}
	
	public function updatepres()
	{
		if ( ! empty($this->_arrParam))
		{
			if ($this->_arrParam['fullname'] == '')
			{
				return 'required';
			}
			$email = new Zend_Validate_EmailAddress();
			if ( ! $email->isValid($this->_arrParam['email']))
			{
				return 'invalidemail';
			}
			
			if ($this->isExists())
			{
				return 'exist';
			}
			$group = $this->getGroup();
			$where = 'id = ' . $this->_arrParam['id'];
			
			$row =  $this->fetchRow($where);
			$row->full_name = $this->_arrParam['fullname'];
			$row->email = $this->_arrParam['email'];
			$row->group_id = $group['id'];
			$row->status = ($this->_arrParam['id'] == 1) ? 1 : $this->_arrParam['status'];
			$row->save();
			
			// optimize table
			$this->_db->query("OPTIMIZE TABLE `users`");
			// delete cache ??? ko luu cache thanh vien nen ko can xoa
			return 'ok';
		}
	}
	
	private function isExists()
	{
		$select = $this->_db->select()
				->from('users', array('id'))
				->where('id != ?', $this->_arrParam['id'], INTEGER)
				->where('email = ?', $this->_arrParam['email'], STRING)
				->limit(1);
		$result = $this->_db->fetchRow($select);
		return ( ! empty($result)) ? true : false;
	}
	
	private function getGroup()
	{
		$select = $this->_db->select()
				->from('user_group', array('id'))
				->where('id = ?', $this->_arrParam['group'], INTEGER)
				->orWhere('group_name = ?', $this->_arrParam['group'], STRING)
				->limit(1);
		$result = $this->_db->fetchRow($select);
		return $result;
	}
	
	public function deletepres()
	{
		$idpres = stripslashes($this->_arrParam['ids']);
		$idpres = json_decode($idpres);
		if (sizeof($idpres) == 1)
		{				
			// khong duoc xoa thanh vien co id la 1 (Administrator)
			if ($idpres[0] != 1)
			{
				$where = ' id = ' . $idpres[0];
				$this->delete($where);	
			}
			else
			{
				return 'no';	
			}
		} 
		else 
		{
			$id_array = array_keys($idpres, 1);
			if ( ! empty($id_array))
			{
				unset($idpres[$id_array[0]]);
			}
			$new_id = implode(',', $idpres);
			$where = 'id IN (' .$new_id. ')';
			$this->delete($where);
		}
		// optimeize tat ca cac table bi thay doi du lieu...
		$this->_db->query("OPTIMIZE TABLE `users`");
		return 'ok';
	}
}